package com.zoe.app;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.StrUtil;
import com.zoe.app.annotation.DataFilter;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zoe.Zhang
 * @date 2022/05/26
 * @description
 */
// @Aspect
// @Component
public class DataAspect {

    /**
     * within：方法注解+类注解都能用
     * annotation：只能扫描到方法上面的注解
     */
    // @Pointcut(value = "@within(com.zoe.app.annotation.DataFilter)")
    @Pointcut(value = "@annotation(com.zoe.app.annotation.DataFilter)")
    public void joinPoints() {
    }

111111
    @SneakyThrows
    @Around(value = "joinPoints()")
    public Object aroundPoint(ProceedingJoinPoint proceedingJoinPoint) {

        Object o = proceedingJoinPoint.proceed();

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        // 拿到切点的方法
        Method method = signature.getMethod();

        DataFilter annotation = AnnotationUtil.getAnnotation(method, DataFilter.class);
        if (annotation.enable()) {
            String filterValue = annotation.filterValue();
            if (o instanceof List) {
                List<?> o1 = (List<?>) o;
                o = o1.stream()
                      .filter(st -> !StrUtil.contains(st.toString(), filterValue))
                      .collect(Collectors.toList());
            }
        }
        return o;
    }

}
